<?php

namespace App\Services\Applet\Order;

use App\Exceptions\CartException;
use App\Exceptions\ShopException;
use App\Helpers\Helper;
use App\Helpers\MvcHelper;
use App\Models\Applet\Order\ShopMasterOrderModel;
use App\Models\Applet\Order\ShopOrderExpressModel;
use App\Models\Applet\Order\ShopOrderModel;
use App\Models\Applet\Other\PaymentOrderModel;
use App\Models\Applet\User\UserIntegralRecordsModel;
use Exception;
use Illuminate\Support\Facades\DB;

class ShopOrderService extends BaseOrderService implements OrderInterface
{

    /**
     * 创建订单
     * @param array $params
     * @return array
     * @throws ShopException
     * @throws Exception
     */
    public function create(array $params): array
    {
        // 添加操作锁
        if (!$this->lockOperate('shopOrderGoodsId', $params['goodsId'])) {
            throw new ShopException('操作频繁，请稍后重试', ShopException::CODE_6001);
        }

        try {
            $integral = $params['integral'] ?? 0;

            // 查询商品信息
            $goodsInfo = $this->getShopGoodsModel()->getItemById($params['goodsId'], [
                'id', 'category_id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'params', 'quantity', 'weight', 'shipping_fee'
            ]);
            if (empty($goodsInfo)) {
                throw new ShopException('商品不存在', ShopException::CODE_1001);
            }

            if ($goodsInfo['quantity'] < $params['quantity']) {
                throw new ShopException('商品库存不足', ShopException::CODE_1007);
            }

            // 查询用户积分
            $userInfo = $this->getUserModel()->getItemById(MvcHelper::getLoginUserId(), [
                'id', 'integral'
            ]);

            if ($userInfo['integral'] < $integral) {
                throw new ShopException('剩余积分不足', ShopException::CODE_1002);
            }

            // 查询用户收货地址
            $userAddress = $this->getUserAddressModel()->getItemByUserIdAndId(MvcHelper::getLoginUserId(), $params['userAddressId'], [
                'id', 'receive_name', 'receive_tel', 'area_info', 'address', 'province_id', 'city_id', 'region_id'
            ]);
            if (empty($userAddress)) {
                throw new ShopException('用户收货地址不存在', ShopException::CODE_1003);
            }

            // 订单总金额
            $shippingFee = ($goodsInfo['shipping_fee'] * $params['quantity']);
            $totalPrice = ($goodsInfo['price'] * $params['quantity']) + $shippingFee;
            // 订单金额
            $orderPrice = $totalPrice - $integral;
            if ($orderPrice < 0) {
                throw new ShopException('使用积分不能超过商品本身价格', ShopException::CODE_1009);
            }

            // 主订单
            $createMasterOrder = [
                'user_id' => MvcHelper::getLoginUserId(),
                'order_no' => Helper::createOrderNo("SHN"),
                'total_price' => $totalPrice,
                'order_price' => $orderPrice,
                'order_integral' => $integral,
                'shipping_fee' => $shippingFee,
            ];

            // 订单收货地址
            $createOrderAddress = [
                'user_id' => MvcHelper::getLoginUserId(),
                'user_address_id' => $userAddress['id'],
                'receive_name' => $userAddress['receive_name'],
                'receive_tel' => $userAddress['receive_tel'],
                'area_info' => $userAddress['area_info'],
                'address' => $userAddress['address'],
                'province_id' => $userAddress['province_id'],
                'city_id' => $userAddress['city_id'],
                'region_id' => $userAddress['region_id'],
            ];

            // 子订单
            $createSubOrder = [
                'order_master_id' => 0,
                'goods_id' => $goodsInfo['id'],
                'order_no' => Helper::createOrderNo("SHN"),
                'goods_price' => $goodsInfo['price'],
                'total_price' => $totalPrice,
                'order_price' => $orderPrice,
                'order_integral' => $integral,
                'quantity' => $params['quantity'],
            ];

            // 订单商品
            $createOrderGoods = [
                'category_id' => $goodsInfo['category_id'],
                'goods_id' => $goodsInfo['id'],
                'order_master_id' => 0,
                'order_id' => 0,
                'province_id' => $goodsInfo['province_id'],
                'city_id' => $goodsInfo['city_id'],
                'region_id' => $goodsInfo['region_id'],
                'name' => $goodsInfo['name'],
                'price' => $goodsInfo['price'],
                'cover_img' => $goodsInfo['cover_img'],
                'weight' => $goodsInfo['weight'],
                'shipping_fee' => $goodsInfo['shipping_fee'],
                'params' => $goodsInfo['params'],
            ];


            DB::transaction(function () use ($createSubOrder, $createMasterOrder, $createOrderGoods, $createOrderAddress) {
                // 创建主订单
                $orderMasterId = $this->getShopMasterOrderModel()->addItemGetId($createMasterOrder);
                $createSubOrder['order_master_id'] = $orderMasterId;
                $createOrderAddress['order_master_id'] = $orderMasterId;

                // 创建订单收货地址
                $this->getShopOrderAddressModel()->addItemGetId($createOrderAddress);

                // 创建子订单
                $orderId = $this->getShopOrderModel()->addItemGetId($createSubOrder);
                $createOrderGoods['order_master_id'] = $orderMasterId;
                $createOrderGoods['order_id'] = $orderId;
                // 创建订单商品
                $this->getShopOrderGoodsModel()->addItem($createOrderGoods);

                // 扣商品库存
                $this->getShopGoodsModel()->updateItemById($createSubOrder['goods_id'], [
                    'quantity' => DB::raw(sprintf('quantity - %s', $createSubOrder['quantity'])),
                    'sales_quantity' => DB::raw(sprintf('sales_quantity + %s', $createSubOrder['quantity'])),
                ]);

                // 添加扣积分记录
                if ($createMasterOrder['order_integral'] != 0) {
                    // 扣积分库存
                    $this->getUserModel()->updateItemById($createMasterOrder['user_id'], [
                        'integral' => DB::raw(sprintf('integral - %s', $createMasterOrder['order_integral'])),
                    ]);

                    $this->getUserIntegralRecordsModel()->addItem([
                        'user_id' => MvcHelper::getLoginUserId(),
                        'type' => UserIntegralRecordsModel::TYPE_DECREMENT,
                        'source_type' => UserIntegralRecordsModel::SOURCE_TYPE_USE,
                        'source_id' => $orderMasterId,
                        'quantity' => $createMasterOrder['order_integral'],
                        'remark' => '商城使用积分'
                    ]);
                }
            });

            $this->unlockOperate('shopOrderGoodsId', $params['goodsId']);
            return [
                'orderNo' => $createMasterOrder['order_no'],
            ];
        } catch (Exception $exception) {
            $this->unlockOperate('shopOrderGoodsId', $params['goodsId']);
            throw $exception;
        }
    }

    /**
     * 购物车创建订单
     * @return void
     * @throws Exception
     */
    public function cartCreate(array $params): array
    {
        // 添加操作锁
        if (!$this->lockOperate('shopOrderCartUserId', MvcHelper::getLoginUserId())) {
            throw new ShopException('操作频繁，请稍后重试', ShopException::CODE_6001);
        }

        try {
            // 购物车ids
            $cartIds = array_column($params['cartList'], 'id');

            // 查询购物车是否存在
            $cartList = $this->getCartModel()->getItemsByUserIdAndIds(MvcHelper::getLoginUserId(), $cartIds, [
                'id', 'goods_id', 'quantity'
            ]);
            if (count($cartList) != count($cartIds)) {
                throw new CartException('购物车数据刷新，请刷新后重试', CartException::CODE_1002);
            }

            // 查询用户收货地址
            $userAddress = $this->getUserAddressModel()->getItemByUserIdAndId(MvcHelper::getLoginUserId(), $params['userAddressId'], [
                'id', 'receive_name', 'receive_tel', 'area_info', 'address', 'province_id', 'city_id', 'region_id'
            ]);
            if (empty($userAddress)) {
                throw new ShopException('用户收货地址不存在', ShopException::CODE_1003);
            }

            $paramsCartList = array_column($params['cartList'], null, 'id');

            $cartListMap = [];
            $totalGoodsQuantityList = [];
            foreach ($cartList as $item) {
                if (empty($cartListMap[$item['goods_id']])) {
                    $totalGoodsQuantityList[$item['goods_id']] = $item['quantity'];
                    $cartListMap[$item['goods_id']] = $item;
                    $cartListMap[$item['goods_id']]['integral'] = $paramsCartList[$item['id']]['integral'];
                } else {
                    $totalGoodsQuantityList[$item['goods_id']] += $item['quantity'];
                    $cartListMap[$item['goods_id']]['integral'] += $paramsCartList[$item['id']]['integral'];
                }
            }

            $goodsIds = array_column($cartList, 'goods_id');

            // 查询商品列表
            $goodsList = $this->getShopGoodsModel()->getItemsByIds($goodsIds, [
                'id', 'category_id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'params', 'quantity', 'weight', 'shipping_fee'
            ]);

            if (count(array_unique($goodsIds)) != count($goodsList)) {
                throw new CartException('商品失效，请刷新后重试', CartException::CODE_1003);
            }

            $goodsListMap = array_column($goodsList, null, 'id');
            foreach ($totalGoodsQuantityList as $index => $item) {
                if ($item > $goodsListMap[$index]['quantity']) {
                    throw new CartException('商品库存不足，请稍后重试', CartException::CODE_1004);
                }
            }

            $orderMasterOrder = [
                'user_id' => MvcHelper::getLoginUserId(),
                'order_no' => Helper::createOrderNo("SPN"),
                'total_price' => 0,
                'order_price' => 0,
                'order_integral' => 0,
                'shipping_fee' => 0,
            ];

            // 订单收货地址
            $createOrderAddress = [
                'user_id' => MvcHelper::getLoginUserId(),
                'user_address_id' => $userAddress['id'],
                'receive_name' => $userAddress['receive_name'],
                'receive_tel' => $userAddress['receive_tel'],
                'area_info' => $userAddress['area_info'],
                'address' => $userAddress['address'],
                'province_id' => $userAddress['province_id'],
                'city_id' => $userAddress['city_id'],
                'region_id' => $userAddress['region_id'],
            ];

            $orderSubOrders = [];
            $orderGoods = [];
            foreach ($goodsList as $item) {
                $integral = $cartListMap[$item['id']]['integral'] ?? 0;
                $shippingFee = ($item['shipping_fee'] * $cartListMap[$item['id']]['quantity']);
                $totalPrice = ($item['price'] * $cartListMap[$item['id']]['quantity']) + $shippingFee;
                $orderPrice = $totalPrice - $integral;
                if ($orderPrice < 0) {
                    throw new ShopException('使用积分不能超过商品本身价格', ShopException::CODE_1009);
                }

                $orderSubOrders[] = [
                    'order_master_id' => 0,
                    'goods_id' => $item['id'],
                    'order_no' => Helper::createOrderNo("SPN"),
                    'goods_price' => $item['price'],
                    'total_price' => $totalPrice,
                    'order_price' => $orderPrice,
                    'order_integral' => $integral,
                    'quantity' => $cartListMap[$item['id']]['quantity'],
                ];

                // 订单商品
                $orderGoods[$item['id']] = [
                    'category_id' => $item['category_id'],
                    'goods_id' => $item['id'],
                    'order_master_id' => 0,
                    'order_id' => 0,
                    'province_id' => $item['province_id'],
                    'city_id' => $item['city_id'],
                    'region_id' => $item['region_id'],
                    'name' => $item['name'],
                    'price' => $item['price'],
                    'cover_img' => $item['cover_img'],
                    'weight' => $item['weight'],
                    'shipping_fee' => $item['shipping_fee'],
                    'params' => $item['params'],
                ];

                $orderMasterOrder['total_price'] += $totalPrice;
                $orderMasterOrder['order_price'] += $orderPrice;
                $orderMasterOrder['order_integral'] += $integral;
                $orderMasterOrder['shipping_fee'] += $shippingFee;
            }


            DB::transaction(function () use ($params, $cartIds, $orderMasterOrder, $orderSubOrders, $orderGoods, $createOrderAddress) {
                // 添加主订单
                $orderMasterId = $this->getShopMasterOrderModel()->addItemGetId($orderMasterOrder);

                // 添加订单用户地址
                $createOrderAddress['order_master_id'] = $orderMasterId;
                $this->getShopOrderAddressModel()->addItemGetId($createOrderAddress);

                foreach ($orderSubOrders as $item) {
                    $item['order_master_id'] = $orderMasterId;
                    // 添加子订单
                    $orderId = $this->getShopOrderModel()->addItemGetId($item);
                    $orderGoods[$item['goods_id']]['order_master_id'] = $orderMasterId;
                    $orderGoods[$item['goods_id']]['order_id'] = $orderId;
                    // 添加订单商品
                    $this->getShopOrderGoodsModel()->addItem($orderGoods[$item['goods_id']]);
                    // 扣商品库存
                    $this->getShopGoodsModel()->updateItemById($item['goods_id'], [
                        'quantity' => DB::raw(sprintf('quantity - %s', $item['quantity'])),
                        'sales_quantity' => DB::raw(sprintf('sales_quantity + %s', $item['quantity'])),
                    ]);
                }

                if ($orderMasterOrder['order_integral'] != 0) {
                    // 扣积分库存
                    $this->getUserModel()->updateItemById($orderMasterOrder['user_id'], [
                        'integral' => DB::raw(sprintf('integral - %s', $orderMasterOrder['order_integral'])),
                    ]);
                    // 添加扣积分记录
                    $this->getUserIntegralRecordsModel()->addItem([
                        'user_id' => MvcHelper::getLoginUserId(),
                        'type' => UserIntegralRecordsModel::TYPE_DECREMENT,
                        'source_type' => UserIntegralRecordsModel::SOURCE_TYPE_USE,
                        'source_id' => $orderMasterId,
                        'quantity' => $orderMasterOrder['order_integral'],
                        'remark' => '商城使用积分'
                    ]);
                }

                // 删除购物车数据
                $this->getCartModel()->deleteItemsByIds($cartIds);
            });
            $this->unlockOperate('shopOrderCartUserId', MvcHelper::getLoginUserId());
            return [
                'orderNo' => $orderMasterOrder['order_no'],
            ];
        } catch (Exception $exception) {
            $this->unlockOperate('shopOrderCartUserId', MvcHelper::getLoginUserId());
            throw $exception;
        }
    }

    /**
     * 取消订单
     * @return void
     * @throws Exception
     */
    public function cancel(array $params)
    {
        // 查询订单
        $orderData = $this->getShopOrderModel()->getItemById($params['id'], [
            'id', 'order_master_id', 'goods_id', 'quantity', 'order_integral'
        ]);
        if (empty($orderData)) {
            throw new ShopException('订单不存在', ShopException::CODE_1004);
        }

        // 查询主订单
        $orderMasterData = $this->getShopMasterOrderModel()->getItemById($orderData['order_master_id'], [
            'id', 'user_id'
        ]);

        // 取消订单
        DB::transaction(function () use ($orderData, $orderMasterData, $params) {
            // 删除主订单
            $this->getShopMasterOrderModel()->deleteItemById($orderData['order_master_id']);
            // 取消订单
            $this->getShopOrderModel()->cancel($params['id']);
            // 回滚商品数量
            $this->getShopGoodsModel()->updateItemById($orderData['goods_id'], [
                'quantity' => DB::raw(sprintf('quantity + %s', $orderData['quantity'])),
            ]);
            // 回滚用户积分
            $this->getUserModel()->updateItemById($orderMasterData['user_id'], [
                'integral' => DB::raw(sprintf('integral + %s', $orderData['order_integral'])),
            ]);
            // 删除用户使用积分记录
            $this->getUserIntegralRecordsModel()->deleteItemByUserIdAndSourceId(MvcHelper::getLoginUserId(), $orderMasterData['user_id']);
        });
    }

    /**
     * 删除订单
     * @return void
     * @throws ShopException
     * @throws Exception
     */
    public function delete(array $params)
    {
        // 查询订单
        $orderData = $this->getShopOrderModel()->getItemById($params['id'], [
            'id', 'order_status'
        ]);
        if (empty($orderData)) {
            throw new ShopException('订单不存在', ShopException::CODE_1004);
        }

        if ($orderData['order_status'] != ShopOrderModel::ORDER_STATUS_CANCEL &&
            $orderData['order_status'] != ShopOrderModel::ORDER_STATUS_COMPLETED) {
            throw new ShopException('状态不允许操作', ShopException::CODE_1008);
        }

        // 取消订单
        $this->getShopOrderModel()->deleteItemById($params['id']);
    }

    /**
     * 确认收货
     * @param array $params
     * @return void
     * @throws ShopException
     * @throws Exception
     */
    public function confirm(array $params)
    {
        // 查询订单
        $orderData = $this->getShopOrderModel()->getItemById($params['id']);
        if (empty($orderData)) {
            throw new ShopException('订单不存在', ShopException::CODE_1004);
        }

        // 更新订单状态
        $this->getShopOrderModel()->updateItemById($params['id'], [
            'order_status' => ShopOrderModel::ORDER_STATUS_COMPLETED,
        ]);
    }

    /**
     * 订单列表
     * @param array $params
     * @return array[]
     * @throws Exception
     */
    public function list(array $params): array
    {
        $params['userId'] = MvcHelper::getLoginUserId();
        // 查询订单列表
        $orderList = $this->getShopMasterOrderModel()->list($params, [
            'shop_orders.id', 'order_master_id', 'shop_orders.order_no', 'shop_orders.goods_price',
            'shop_orders.total_price', 'shop_orders.order_price', 'shop_orders.quantity',
            'shop_orders.order_status', 'shop_orders.remark'
        ]);

        $orderIds = array_column($orderList, 'id');

        // 查询订单商品
        $orderGoodsList = $this->getShopOrderGoodsModel()->getItemsByOrderIds($orderIds, [
            'id', 'order_id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'weight', 'shipping_fee'
        ]);
        $orderGoodsListMap = array_column($orderGoodsList, null, 'order_id');

        $list = [];
        foreach ($orderList as $item) {
            $list[] = [
                'id' => $item['id'],
                'orderNo' => $item['order_no'],
                'orderName' => $orderGoodsListMap[$item['id']]['name'],
                'orderImage' => $orderGoodsListMap[$item['id']]['cover_img'],
                'goodsPrice' => $orderGoodsListMap[$item['id']]['price'] / 100,
                'weight' => $orderGoodsListMap[$item['id']]['weight'] / 1000,
                'shippingFee' => ($orderGoodsListMap[$item['id']]['shipping_fee'] / 100) * $item['quantity'],
                'orderPrice' => $item['order_price'] / 100,
                'quantity' => $item['quantity'],
                'orderStatus' => $item['order_status'],
                'remark' => $item['remark'],
            ];
        }

        return [
            'list' => $list,
        ];
    }

    /**
     * 订单详情
     * @param array $params
     * @return array
     * @throws ShopException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询订单
        $orderData = $this->getShopOrderModel()->getItemById($params['id'], [
            'id', 'order_master_id', 'goods_id', 'order_no', 'order_price', 'order_integral', 'quantity', 'order_status', 'remark', 'created_at', 'updated_at'
        ]);
        if (empty($orderData)) {
            throw new ShopException('订单不存在', ShopException::CODE_1004);
        }

        // 查询订单商品
        $orderGoods = $this->getShopOrderGoodsModel()->getItemByOrderIdAndGoodsId($orderData['id'], $orderData['goods_id'], [
            'id', 'order_id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'weight'
        ]);

        // 查询订单收货地址
        $orderUserAddress = $this->getShopOrderAddressModel()->getItemByOrderMasterId($orderData['order_master_id'], [
            'receive_name', 'receive_tel', 'id', 'area_info', 'address'
        ]);

        // 查询物流状态
        $expressInfoData = $this->getShopOrderExpressModel()->getItemByOrderMasterId($orderData['order_master_id'], [
            'id', 'express_company_code', 'express_no', 'phone', 'status'
        ]);

        $expressInfo = [];
        if (!empty($expressInfoData)) {
            $expressList = $this->getExpressApi()->query($expressInfoData['express_company_code'], $expressInfoData['express_no'], $expressInfoData['phone']);
            // 更新物流状态
            $this->getShopOrderExpressModel()->updateItemById($expressInfoData['id'], [
                'status' => ShopOrderExpressModel::STATUS_DELIVERY,
            ]);

            $expressInfo = [
                'expressNo' => $expressInfoData['express_no'],
                'list' => $expressList
            ];
        }

        // 查询主订单
        $orderMasterData = $this->getShopMasterOrderModel()->getItemById($orderData['order_master_id'], [
            'id', 'order_no', 'pay_time', 'total_price', 'shipping_fee', 'created_at'
        ]);

        // 查询支付订单
        $paymentOrder = $this->getPaymentOrderModel()->getItemByOrderId($orderData['order_master_id'], [
            'id', 'pay_type', 'transaction_id', 'pay_time', 'created_at'
        ]);

        $paymentInfo = [];
        if ($paymentOrder) {
            $paymentInfo = [
                'orderNo' => $orderMasterData['order_no'],
                'payType' => PaymentOrderModel::$orderType[$paymentOrder['pay_type']],
                'transactionId' => $paymentOrder['transaction_id'],
                'payTime' => $paymentOrder['pay_time'],
                'createTime' => $paymentOrder['created_at'],
            ];
        }
        if ($orderData['order_status'] == ShopOrderModel::ORDER_STATUS_COMPLETED) {
            if ($orderData['order_price'] == 0) {
                $paymentInfo = [
                    'orderNo' => $orderMasterData['order_no'],
                    'payType' => '积分支付',
                    'transactionId' => '',
                    'payTime' => $orderMasterData['pay_time'],
                    'createTime' => $orderMasterData['pay_time'],
                ];
            } else {
                $paymentInfo = [
                    'orderNo' => $orderMasterData['order_no'],
                    'payType' => '其他',
                    'transactionId' => '',
                    'payTime' => $orderMasterData['pay_time'],
                    'createTime' => $orderMasterData['pay_time'],
                ];
            }
        }

        $areaIds = [$orderGoods['province_id'], $orderGoods['city_id'], $orderGoods['region_id']];

        // 查询地区
        $areaList = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaListMap = array_column($areaList, 'name', 'code');

        //地区名称
        $provinceName = $areaListMap[$orderGoods['province_id']] ?? '';
        $cityName = $areaListMap[$orderGoods['city_id']] ?? '';
        $countyName = $areaListMap[$orderGoods['region_id']] ?? '';
        $areaName = $provinceName . $cityName . $countyName;

        // 取消订单时间
        $cancelTime = $orderData['order_status'] == ShopOrderModel::ORDER_STATUS_CANCEL ? $orderData['updated_at'] : '';
        // 支付时间
        $paymentOrder = $this->getPaymentOrderModel()->getItemByOrderIdAndStatusSuccess($orderData['id'], [
            'id', 'pay_time'
        ]);
        $paymentTime = !empty($paymentInfo) ? $paymentInfo['payTime'] : '';

        return [
            'id' => $orderData['id'],
            'orderNo' => $orderData['order_no'],
            'orderName' => $orderGoods['name'],
            'orderImage' => $orderGoods['cover_img'],
            'goodsPrice' => $orderGoods['price'] / 100,
            'orderPrice' => $orderData['order_price'] / 100,
            'totalPrice' => $orderMasterData['total_price'] / 100,
            'orderIntegral' => $orderData['order_integral'],
            'quantity' => $orderData['quantity'],
            'weight' => $orderGoods['weight'] / 1000,
            'shippingFee' => $orderMasterData['shipping_fee'] / 100,
            'orderStatus' => $orderData['order_status'],
            'areaName' => $areaName,
            'remark' => $orderData['remark'],
            'paymentInfo' => $paymentInfo,
            'addressInfo' => [
                'receiveName' => $orderUserAddress['receive_name'],
                'receiveTel' => $orderUserAddress['receive_tel'],
                'address' => !empty($orderUserAddress) ? $orderUserAddress['area_info'] . $orderUserAddress['address'] : '',
            ],
            'expressInfo' => $expressInfo,
            'createdAt' => $orderData['created_at'],
            'cancelTime' => $cancelTime,
            'paymentTime' => $paymentTime,
        ];
    }

    /**
     * 获取订单详情
     * @param string $orderNo
     * @return array
     * @throws ShopException
     * @throws Exception
     */
    public function getOrderInfo(string $orderNo): array
    {
        $orderData = $this->getShopMasterOrderModel()->getItemByOrderNo($orderNo, [
            'id', 'user_id', 'order_no', 'order_price', 'order_integral'
        ]);

        if (empty($orderData)) {
            // 查询子订单
            $orderInfo = $this->getShopOrderModel()->getItemByOrderNo($orderNo, [
                'id', 'order_master_id', 'total_price', 'order_price'
            ]);
            if (empty($orderInfo)) {
                throw new ShopException('订单不存在', ShopException::CODE_1004);
            }
            // 查询主订单下的订单数量， 大于1，则将之前的主订单置为删除状态，创建新的主订单
            $list = $this->getShopOrderModel()->getItemByOrderMasterIds([$orderInfo['order_master_id']]);
            if (count($list) > 1) {
                // 主订单
                $orderData = [
                    'user_id' => MvcHelper::getLoginUserId(),
                    'order_no' => Helper::createOrderNo("SPN"),
                    'total_price' => $orderInfo['total_price'],
                    'order_price' => $orderInfo['order_price'],
                    'order_integral' => $orderInfo['order_integral'],
                ];

                DB::beginTransaction();
                // 删除之前的主订单
                $this->getShopMasterOrderModel()->deleteItemById($orderInfo['order_master_id']);
                // 创建新的主订单
                $orderMasterId = $this->getShopMasterOrderModel()->addItemGetId($orderData);
                $orderData['id'] = $orderMasterId;
                // 将子订单的关系绑到新订单
                $this->getShopOrderModel()->updateItemById($orderInfo['order_master_id'], [
                    'order_master_id' => $orderMasterId,
                ]);
                DB::commit();
            } else {
                $orderData = $this->getShopMasterOrderModel()->getItemById($orderInfo['order_master_id'], [
                    'id', 'user_id', 'order_no', 'order_price', 'order_integral'
                ]);
            }
        }

        return [
            'id' => $orderData['id'],
            'user_id' => $orderData['user_id'],
            'order_no' => $orderData['order_no'],
            'order_price' => $orderData['order_price'],
        ];
    }

    /**
     * 根据主订单号获取订单详情
     *
     * @return void
     * @throws Exception
     */
    public function getOrderInfoByOrderMasterNo(string $orderNo): array
    {
        $orderMasterInfo = $this->getShopMasterOrderModel()->getItemByOrderNo($orderNo, [
            'id', 'user_id', 'order_no', 'order_price', 'order_integral'
        ]);

        $orderInfo = $this->getShopOrderModel()->getItemByOrderMasterId($orderMasterInfo['id'], [
            'id', 'goods_id', 'quantity',
        ]);

        return [
            'id' => $orderInfo['id'],
            'order_master_id' => $orderMasterInfo['id'],
            'user_id' => $orderMasterInfo['user_id'],
            'goods_id' => $orderInfo['goods_id'],
            'order_no' => $orderMasterInfo['order_no'],
            'order_price' => $orderMasterInfo['order_price'],
            'order_integral' => $orderMasterInfo['order_integral'],
            'quantity' => $orderInfo['quantity'],
        ];
    }

    /**
     * 更新订单状态
     *
     * @return void
     * @throws Exception
     */
    public function updateOrderStatus(int $orderMasterId)
    {
        // 更新主订单
        $this->getShopMasterOrderModel()->updateItemById($orderMasterId, [
            'order_status' => ShopMasterOrderModel::ORDER_STATUS_SUCCESS,
            'pay_status' => ShopMasterOrderModel::PAY_STATUS_SUCCESS,
            'pay_time' => date('Y-m-d H:i:s'),
        ]);

        // 更新子订单
        $this->getShopOrderModel()->updateItemByOrderMasterId($orderMasterId, [
            'order_status' => ShopOrderModel::ORDER_STATUS_SUCCESS,
        ]);
    }
}
